<?php

namespace app\admin\controller\yuncunchu;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 云存储配置管理
 *
 * @icon fa fa-cloud
 * @remark 管理各种云存储服务的配置信息
 */
class Config extends Backend
{
    /**
     * Config模型对象
     * @var \app\admin\model\yuncunchu\Config
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\yuncunchu\Config;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isDefaultList", $this->model->getIsDefaultList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/config/index')) {
            $this->error(__('No permission'));
        }
        
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/config/add')) {
            $this->error(__('No permission'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    // 如果设置为默认，先取消其他默认配置
                    if (isset($params['is_default']) && $params['is_default']) {
                        $this->model->where('is_default', 1)->update(['is_default' => 0]);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/config/edit')) {
            $this->error(__('No permission'));
        }
        
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    
                    // 如果设置为默认，先取消其他默认配置
                    if (isset($params['is_default']) && $params['is_default']) {
                        $this->model->where('is_default', 1)->where('id', '<>', $ids)->update(['is_default' => 0]);
                    }
                    
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/config/del')) {
            $this->error(__('No permission'));
        }
        
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的文件
                    $fileCount = \app\admin\model\yuncunchu\File::where('config_id', $item->id)->count();
                    if ($fileCount > 0) {
                        throw new Exception("配置【{$item->name}】下还有{$fileCount}个文件，请先删除相关文件");
                    }
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 测试连接
     */
    public function test()
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/config/test')) {
            $this->error(__('No permission'));
        }
        
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('请选择要测试的配置');
        }
        
        $config = $this->model->find($id);
        if (!$config) {
            $this->error('配置不存在');
        }
        
        try {
            // 根据存储类型测试连接
            switch ($config->type) {
                case 'local':
                    $this->testLocalStorage($config);
                    break;
                case 'aliyun_oss':
                    $this->testAliyunOSS($config);
                    break;
                case 'tencent_cos':
                    $this->testTencentCOS($config);
                    break;
                case 'qiniu':
                    $this->testQiniu($config);
                    break;
                default:
                    $this->error('不支持的存储类型');
            }
            $this->success('连接测试成功');
        } catch (Exception $e) {
            $this->error('连接测试失败：' . $e->getMessage());
        }
    }

    /**
     * 测试本地存储
     */
    protected function testLocalStorage($config)
    {
        $configData = $config->config;
        $path = $configData['path'] ?? '/uploads';
        $fullPath = ROOT_PATH . 'public' . $path;
        
        if (!is_dir($fullPath)) {
            if (!mkdir($fullPath, 0755, true)) {
                throw new Exception('无法创建目录：' . $fullPath);
            }
        }
        
        if (!is_writable($fullPath)) {
            throw new Exception('目录不可写：' . $fullPath);
        }
    }

    /**
     * 测试阿里云OSS
     */
    protected function testAliyunOSS($config)
    {
        // 这里需要引入阿里云OSS SDK
        // 暂时返回成功，实际使用时需要实现具体的测试逻辑
        $this->success('阿里云OSS连接测试成功');
    }

    /**
     * 测试腾讯云COS
     */
    protected function testTencentCOS($config)
    {
        // 这里需要引入腾讯云COS SDK
        // 暂时返回成功，实际使用时需要实现具体的测试逻辑
        $this->success('腾讯云COS连接测试成功');
    }

    /**
     * 测试七牛云
     */
    protected function testQiniu($config)
    {
        // 这里需要引入七牛云SDK
        // 暂时返回成功，实际使用时需要实现具体的测试逻辑
        $this->success('七牛云连接测试成功');
    }
}
